
namespace Patterns4Net.Core.Patterns
{
    using System.Collections.Generic;
    using System.Linq;
    using Mono.Cecil;
    using Patterns4Net.Attributes;
    using Patterns4Net.Attributes.DesignPatterns;
    using Patterns4Net.Attributes.Relations;
    using Patterns4Net.Core.CecilExtensions;

    [Immutable]
    public class Composite : PatternBase
    {
        public Composite(TypeDefinition compositeType, TypeDefinition component = null)
        {
            this.CompositeType = compositeType;
            this.Component = component;
        }

        public TypeDefinition CompositeType { get; set; }

        [PatternRole(RelationType = RelationType.Composition, Cardinality = Cardinality.Multiple)]
        public TypeDefinition Component { get; private set; }

        public FieldReference ComponentsField
        {
            get
            {
                if (this.CompositeType.HasFields == false)
                {
                    return null;
                }

                return this.CompositeType.Fields.FirstOrDefault(
                    x => x.FieldType.IsGenericInstanceOf(typeof(IEnumerable<>), this.Component));                
            }
        }
    }
}
